/**
 * 版权所有 2009-2015 中国中医科学院中医药信息研究所 何前锋 frontpeak@yahoo.com.cn
 **/
package cn.ac.cintcm.sh.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import cn.ac.cintcm.prespring.util.Config;
import cn.ac.cintcm.sh.domain.AvgDosage;
import cn.ac.cintcm.sh.domain.Dosage;
import cn.ac.cintcm.sh.domain.HerbEntry;
import cn.ac.cintcm.sh.domain.Unit;
import cn.ac.cintcm.sh.service.AliasService;

public class HerbDao {
    
    private HsqldbDao dao = (new HsqldbDao()).getDao();
    
    
    public HashMap<Integer, String>  getNameIndex() {
        HashMap<Integer, String> nameIndex = new HashMap<Integer, String>();
        String sql = "select id, name from herbentry";
        dao.openConnection();
        ResultSet rs=this.dao.executeQuery(sql);
        try {
            while (rs.next()) {
                Integer id = rs.getInt(1);
                String name = rs.getString(2);
                nameIndex.put(id, name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dao.closeConnection();
        }
        return nameIndex;
    }

    /**
     * 取得所有的中药
     * @return
     */
    public List<HerbEntry> getHerbs() {
        List<HerbEntry> nodes = new ArrayList<HerbEntry>();
        String sql="select * from herbentry";
        dao.openConnection();
        ResultSet rs=this.dao.executeQuery(sql);
        try{
            while(rs.next()){
                int id=rs.getInt("id");
                String name=rs.getString("name");
                HerbEntry node=new HerbEntry();
                node.setId(id);
                node.setName(name);
                node.setMinDosage(rs.getFloat("MINDOSAGE"));
                node.setMaxDosage(rs.getFloat("MAXDOSAGE"));
                node.setQi(rs.getString("qi"));
                node.setWei(string2List(rs.getString("wei")));
                node.setJing(string2List(rs.getString("jing")));
                node.setXiao(string2List(rs.getString("xiao")));
                node.setQiValue(rs.getFloat("HOTVALUE"));
                node.setUnit(rs.getString("UNIT"));
                nodes.add(node);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        dao.closeConnection();
        return nodes;
    }

    private List<String> string2List(String str) {
        List<String> strList = null;
        if (str != null) {
            String[] array = str.split("\\|");
            if (array != null) {
                strList = Arrays.asList(array);
            }
        }
        return strList;
    }

    public List<HerbEntry> getHerbs(String name, boolean precise, boolean extended) {
        List<HerbEntry> nodes = new ArrayList<HerbEntry>();

        String sql="select * from herbentry where name ";
        if (precise) {
            
            if (extended) {
                List<String> list = AliasService.getInformal(name);
                if (list != null) {
                    StringBuilder sb = new StringBuilder();
                    for (String s : list) {
                        sb.append("='");
                        
                        sb.append(s);
                        sb.append("' or name");
                    }
                    int length = " or name".length();
                    sb.delete(sb.length()-length - 1, sb.length());
                    sql = sql + sb.toString();
                   
                }
                
            } else {
                sql = sql + "='" + name;
            }
        } else {
            sql = sql + " like '%" + name + "%";
        }
        sql = sql + "'";
        dao.openConnection();
        ResultSet rs=this.dao.executeQuery(sql);
        try{
            while(rs.next()){
                int id=rs.getInt("id");
                String names = rs.getString("name");
                HerbEntry node = new HerbEntry();
                node.setId(id);
                node.setName(names);
                node.setMinDosage(rs.getFloat("MINDOSAGE"));
                node.setMaxDosage(rs.getFloat("MAXDOSAGE"));
                node.setQi(rs.getString("qi"));
                node.setWei(string2List(rs.getString("wei")));
                node.setJing(string2List(rs.getString("jing")));
                node.setXiao(string2List(rs.getString("xiao")));
                node.setQiValue(rs.getFloat("HOTVALUE"));
                node.setUnit(rs.getString("UNIT"));
                nodes.add(node);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        dao.closeConnection();
        return nodes;

    }

    public List<HerbEntry> getHerbs(float minv, float maxv) {
        List<HerbEntry> nodes = new ArrayList<HerbEntry>();
        String sql="select id, name,hotvalue from herbentry where HOTVALUE between " + minv + " and " + maxv;
        dao.openConnection();
        ResultSet rs=this.dao.executeQuery(sql);
        try{
            while(rs.next()){
                int id=rs.getInt("id");
                String name=rs.getString("name");
                float hcValue = rs.getFloat("hotvalue");
                HerbEntry node=new HerbEntry();
                node.setId(id);
                node.setName(name);
                node.setQiValue(hcValue);
                nodes.add(node);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        dao.closeConnection();
        return nodes;
    }

    public List<HerbEntry> getHerbs(List<String> herbNames) {
        List<HerbEntry> herbs = null;
        if(herbNames != null) {
            herbs=new ArrayList<HerbEntry>();
             this.dao.openConnection();
             StringBuffer sql = new StringBuffer("select * from herbentry where name in(");
             for (String name : herbNames) {
                 sql.append("'");
                 sql.append(name);
                 sql.append("',");
             }
             sql.deleteCharAt(sql.length() - 1);
             sql.append(")");
             ResultSet rs = dao.executeQuery(sql.toString());
             try{
                 while(rs.next()){
                     int id = rs.getInt("id");
                     String name = rs.getString("name");
                     String unit = rs.getString("unit");
                     float minDosage = rs.getFloat("mindosage");
                     float maxDosage = rs.getFloat("maxdosage");
                     String qi = rs.getString("qi");
                     String wei = rs.getString("wei");
                     String jing = rs.getString("jing");
                     String xiao = rs.getString("xiao");
                     float hcValue = rs.getFloat("hotvalue");
                     HerbEntry h = new HerbEntry();
                     h.setId(id);
                     h.setName(name);
                     h.setUnit(unit);
                     h.setMinDosage(minDosage);
                     h.setMaxDosage(maxDosage);
                     h.setQi(qi);
                     if (wei != null) {
                         h.setWei(Arrays.asList(wei.split(Config.ITEM_SPLITTER)));
                     }
                     if (jing != null) {
                         h.setJing(Arrays.asList(jing.split(Config.ITEM_SPLITTER)));
                     }
                     if (xiao != null) {
                         h.setXiao(Arrays.asList(xiao.split(Config.ITEM_SPLITTER)));
                     }
                     h.setQiValue(hcValue);
                     herbs.add(h);
                 }
             }catch(Exception e){
                 e.printStackTrace();
             }
             this.dao.closeConnection();
         }
         return herbs;

    }
    

    /**
     *取得包含了该中药的所有方剂平均剂量
     */
    public AvgDosage getPrescriptionsAvgDosage(String id) {
        AvgDosage avgd = null;
        if (id != null) {
            String sql = "select herb_in_prescription.*, prescription.name " +
                "from herb_in_prescription, prescription where " +
                "prescription.id=herb_in_prescription.prescription_id and id=" + id;
            
            this.dao.openConnection();
            ResultSet rs = dao.executeQuery(sql);
            try{
                avgd = new AvgDosage();
                while(rs.next()){
                    Dosage d = new Dosage();
                    d.setName(rs.getString("name"));
                    Unit u = new Unit();
                    u.setQuantity(rs.getFloat("dosage"));
                    u.setUnit(rs.getString("unit"));
                    d.setUnit(u);
                    avgd.add(d);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            this.dao.closeConnection();
        }
        return avgd;
    }

    public HerbEntry getHerb(String ids) {
        HerbEntry node = null;
        String sql="select * from herbentry where id=" + ids;
        dao.openConnection();
        ResultSet rs=this.dao.executeQuery(sql);
        try{
            while(rs.next()){
                int id=rs.getInt("id");
                String name=rs.getString("name");
                node = new HerbEntry();
                node.setId(id);
                node.setName(name);
                node.setMinDosage(rs.getFloat("MINDOSAGE"));
                node.setMaxDosage(rs.getFloat("MAXDOSAGE"));
                node.setQi(rs.getString("qi"));
                node.setWei(string2List(rs.getString("wei")));
                node.setJing(string2List(rs.getString("jing")));
                node.setXiao(string2List(rs.getString("xiao")));
                node.setQiValue(rs.getFloat("HOTVALUE"));
                node.setUnit(rs.getString("UNIT"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        dao.closeConnection();
        return node;
    }

}